import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hinge/common/index.dart';
import 'package:hinge/common/models/perfume_model.dart';
import 'package:hinge/common/models/video_model.dart';
import 'package:hinge/common/services/chat_service.dart';

// 分享底部弹出框
void showShareBottomSheet({
  required BuildContext context,
  required dynamic content, // 支持VideoModel或PerfumeModel
  bool isVideo = false,
}) {
  final currentUser = UserService.getCurrentUser();
  if (currentUser == null) return;

  // 使用Dialog，并确保显示在底部
  showGeneralDialog(
    context: context,
    barrierDismissible: true,
    barrierLabel: "Share",
    barrierColor: Colors.black.withOpacity(0.5),
    transitionDuration: Duration(milliseconds: 300),
    pageBuilder: (_, __, ___) => Container(), // 不使用这个builder
    transitionBuilder: (context, animation, secondaryAnimation, child) {
      final curvedAnimation = CurvedAnimation(
        parent: animation,
        curve: Curves.easeOutQuad,
      );

      return Align(
        alignment: Alignment.bottomCenter,
        child: SlideTransition(
          position: Tween<Offset>(
            begin: Offset(0, 1), // 从底部滑入
            end: Offset.zero,
          ).animate(curvedAnimation),
          child: ShareBottomSheet(
            currentUserId: currentUser.id,
            content: content,
            isVideo: isVideo,
          ),
        ),
      );
    },
  );
}

class ShareBottomSheet extends StatefulWidget {
  final int currentUserId;
  final dynamic content; // 支持VideoModel或PerfumeModel
  final bool isVideo;

  const ShareBottomSheet({
    Key? key,
    required this.currentUserId,
    required this.content,
    this.isVideo = false,
  }) : super(key: key);

  @override
  State<ShareBottomSheet> createState() => _ShareBottomSheetState();
}

class _ShareBottomSheetState extends State<ShareBottomSheet> {
  List<UserModel> _users = [];
  List<ChatSessionModel> _groupChats = [];
  List<int> _selectedUserIds = [];
  List<String> _selectedGroupIds = [];

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  // 加载用户和群聊数据
  Future<void> _loadData() async {
    // 获取所有用户并排除当前用户
    final users =
        UserService.getAllUsers()
            .where(
              (user) =>
                  user.id != widget.currentUserId &&
                  user.id != UserService.guestUserId,
            )
            .toList();

    // 获取所有群聊
    final chatSessions = await ChatService.getAllChatSessions();
    final groupChats =
        chatSessions
            .where((chat) => chat.type == ChatSessionType.group)
            .toList();

    setState(() {
      _users = users;
      _groupChats = groupChats;
    });
  }

  // 选择/取消选择联系人（可以是用户或群组）
  void _toggleSelection(dynamic contact) {
    if (contact is UserModel) {
      setState(() {
        if (_selectedUserIds.contains(contact.id)) {
          _selectedUserIds.remove(contact.id);
        } else {
          _selectedUserIds.add(contact.id);
        }
      });
    } else if (contact is ChatSessionModel) {
      setState(() {
        if (_selectedGroupIds.contains(contact.id)) {
          _selectedGroupIds.remove(contact.id);
        } else {
          _selectedGroupIds.add(contact.id);
        }
      });
    }
  }

  // 检查联系人是否被选中
  bool _isSelected(dynamic contact) {
    if (contact is UserModel) {
      return _selectedUserIds.contains(contact.id);
    } else if (contact is ChatSessionModel) {
      return _selectedGroupIds.contains(contact.id);
    }
    return false;
  }

  // 分享到选定的用户和群组
  Future<void> _shareContent() async {
    if (_selectedUserIds.isEmpty && _selectedGroupIds.isEmpty) {
      EasyLoading.showInfo('Please select at least one contact');
      return;
    }

    try {
      // 显示加载指示器
      EasyLoading.show(status: 'Sharing...');

      // 将分享内容转换为适合发送的格式
      final perfumeCard =
          widget.isVideo
              ? _convertVideoToPerfumeCard(widget.content as VideoModel)
              : widget.content as PerfumeModel;

      // 分享给选中的用户
      for (final userId in _selectedUserIds) {
        // 找到或创建与该用户的私聊会话
        final chatSession = await ChatService.findOrCreatePrivateChat(
          widget.currentUserId,
          userId,
        );

        // 发送香水卡片消息
        await ChatService.sendMessage(
          chatId: chatSession.id,
          senderId: widget.currentUserId,
          type: MessageType.perfumeCard,
          perfumeCard: perfumeCard,
        );
      }

      // 分享给选中的群聊
      for (final groupId in _selectedGroupIds) {
        // 检查当前用户是否在群聊中
        final isUserInGroup = await ChatService.isUserInChat(
          groupId,
          widget.currentUserId,
        );

        // 如果不在群聊中，先添加
        if (!isUserInGroup) {
          final addResult = await ChatService.addUserToChat(
            groupId,
            widget.currentUserId,
          );

          if (!addResult) {
            // 如果添加失败，跳过该群聊
            EasyLoading.showError('Failed to join group');
            continue;
          }
        }

        // 发送香水卡片消息
        await ChatService.sendMessage(
          chatId: groupId,
          senderId: widget.currentUserId,
          type: MessageType.perfumeCard,
          perfumeCard: perfumeCard,
        );
      }

      // 显示成功提示并关闭弹窗
      EasyLoading.showSuccess('Shared successfully');
      Navigator.pop(context);
    } catch (e) {
      EasyLoading.showError('Failed to share: $e');
    }
  }

  // 将VideoModel转换为PerfumeModel以便发送
  PerfumeModel _convertVideoToPerfumeCard(VideoModel video) {
    // 创建一个安全的PerfumeModel来发送
    return PerfumeModel(
      id: video.id,
      category: 'Video',
      userId: widget.currentUserId,
      title: 'Perfume Video',
      description: video.description,
      isRecommend: true,
      isVideo: true,
      url: "assets/videos/video1.mp4", // 使用固定值避免String?问题
      favoriteCount: video.collectCount,
      likeCount: video.likeCount,
      commentCount: video.commentCount,
    );
  }

  // 获取所有联系人（用户和群组）的合并列表
  List<dynamic> get _allContacts {
    List<dynamic> contacts = [];
    contacts.addAll(_users);
    contacts.addAll(_groupChats);
    return contacts;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 24.h),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment(0.50, -0.00),
          end: Alignment(0.50, 1.00),
          colors: [const Color(0xFFF4F1FF), const Color(0xFFFFEBFB)],
        ),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24.r),
          topRight: Radius.circular(24.r),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题和关闭按钮
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'Share',
                  style: TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                    fontFamily: 'Inter',
                  ),
                ),
                GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: Icon(Icons.close, size: 24.w, color: Colors.black87),
                ),
              ],
            ),
          ),

          SizedBox(height: 24.h),

          // 联系人横向滚动列表
          if (_allContacts.isNotEmpty)
            Container(
              height: 100.h,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                itemCount: _allContacts.length,
                itemBuilder: (context, index) {
                  final contact = _allContacts[index];
                  final bool isSelected = _isSelected(contact);

                  // 获取头像和名称
                  final String avatar =
                      contact is UserModel
                          ? contact.avatar
                          : (contact as ChatSessionModel).avatar ?? '';

                  final String name =
                      contact is UserModel
                          ? contact.nickname
                          : (contact as ChatSessionModel).name;

                  return GestureDetector(
                    onTap: () => _toggleSelection(contact),
                    child: Container(
                      width: 70.w,
                      margin: EdgeInsets.symmetric(horizontal: 8.w),
                      child: Column(
                        children: [
                          // 头像（带选中状态边框）
                          Container(
                            width: 60.w,
                            height: 60.w,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border:
                                  isSelected
                                      ? Border.all(
                                        color: Color(0xFFB197FC),
                                        width: 2.w,
                                      )
                                      : null,
                            ),
                            child: CircleAvatar(
                              radius: 28.w,
                              backgroundImage: AssetImage(avatar),
                            ),
                          ),
                          SizedBox(height: 8.h),
                          // 名称
                          Text(
                            name, // 显示实际的用户名或群组名
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: Colors.black87,
                              fontWeight: FontWeight.w500,
                              fontFamily: 'Inter',
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            )
          else
            Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFB197FC)),
              ),
            ),

          SizedBox(height: 24.h),

          // 确认按钮
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: GestureDetector(
              onTap: _shareContent,
              child: Container(
                alignment: Alignment.center,
                height: 50.h,
                decoration: BoxDecoration(
                  color: Color(0xFFB197FC), // 紫色按钮，与设计图一致
                  borderRadius: BorderRadius.circular(25.r),
                ),
                child: Text(
                  'Sure',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily: 'Inter',
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
